package com.markerhub.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.SysGoods;
import com.markerhub.entity.SysShop;
import com.markerhub.service.SysGoodsService;
import com.markerhub.service.SysShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author jsx on 2023/2/18
 **/
@RestController
@RequestMapping("/sys/goods")
public class SysGoodsController extends BaseController {

    @Autowired
    SysGoodsService sysGoodsService;

    @Autowired
    SysShopService sysShopService;

    //增加
    @PostMapping("/save")
    public Result save(@RequestBody SysGoods sysGoods){
        //将商店名称转化为商店id
        SysShop shop = sysShopService.getShopByName(sysGoods.getShopName());
        if(shop == null){
            return Result.fail("你填写的商品名称不存在，请重新填写或者请先在商店管理界面进行增加");
        }else{
            sysGoods.setShopId(shop.getId());
            sysGoodsService.save(sysGoods);
            return Result.succ("保存商品完成！");
        }
    }

    //查询单条记录
    @GetMapping("/info/{id}")
    public Result getGoods(@PathVariable("id") String id){
        SysGoods goods = sysGoodsService.getGoods(id);
        return Result.succ(goods);
    }

    //修改
    @PostMapping("/update")
    public Result update(@RequestBody  SysGoods sysGoods){
        SysShop shop = sysShopService.getShopByName(sysGoods.getShopName());
        if(shop == null){
            return Result.fail("你填写的商品名称不存在，请重新填写");
        }else{
            sysGoods.setShopId(shop.getId());
            sysGoodsService.updateById(sysGoods);
            return Result.succ("保存商品完成！");
        }
    }

    //删除
    @GetMapping("/delete")
    public Result delete(String id){
        sysGoodsService.removeById(id);
        return Result.succ("删除完成！");
    }

    //分页查询+模糊查询
    @GetMapping("/list")
    public Result list(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String shopName,
            Integer current,
            Integer size
    ){
        Page<SysGoods> list = sysGoodsService.getList(getPage(current,size),name,shopName);
        return Result.succ(list);
    }

}
